/*
   This file is part of the 'Let's Do Stuff Together' project
   http://code.google.com/p/dostufftogether/

   Copyright 2010 Christoph Fuchs, Stefan Thaler

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.sti2.letsdostuff.util;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

/**
 * Helper class to query the activity server 
 * 
 * @author Christoph 'Gigi' Fuchs
 *
 */
public class QueryHelper {

	/**
	 * Query the activity server for activities near you. Using HTTP GET.
	 * 
	 * @param context
	 *            the activity context
	 * @param httpGetRequestURL
	 *            query string
	 * 
	 * @return the response body. Depending on the query this is either the json
	 *         representation of the <code>Activity</code> instances or a simple
	 *         HTML message body. <code>null</code> if unsuccessful
	 */
	public static String queryServer(Context context, String httpGetRequestURL) {
		DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

		try {
			Log.i("QueryHelper", "Encoding URL to utf-8...");
			HttpGet httpGet = new HttpGet(httpGetRequestURL);
			Log.i("QueryHelper", "Trying to build up HTTP GET request...");
			Log.i("QueryHelper", httpGetRequestURL);
			HttpResponse response = defaultHttpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();

			Log.i("QueryHelper", "Server response " + statusCode);

			if (statusCode == HttpStatus.SC_OK) {
				Log.i("QueryHelper", "Server responded with " + HttpStatus.SC_OK
						+ " (OK)");

				HttpEntity entity = response.getEntity();
				byte[] body = null;
				if (entity != null) {
					try {
						if (entity.getContentLength() > 0) {
							body = new byte[(int) entity.getContentLength()];
							DataInputStream dis = new DataInputStream(entity
									.getContent());
							try {
								dis.readFully(body);
							} finally {
								try {
									dis.close();
								} catch (IOException e) {
									Log.e("QueryHelper",
											"Error closing input stream: "
													+ e.getMessage());
								}
							}
						}
					} finally {
						if (entity != null) {
							entity.consumeContent();
						}
					}

					Log.v("QueryHelper", "Response body: "
							+ new String(body));

					return new String(body);
				}
			}
		} catch (ClientProtocolException e) {
			Toast toast = Toast.makeText(context,
					"Could not connect to server. Reason: " + e.getMessage(),
					Toast.LENGTH_SHORT);
			toast.show();
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			Toast toast = Toast.makeText(context,
					"Encoding error. Reason: " + e.getMessage(),
					Toast.LENGTH_SHORT);
			toast.show();
			e.printStackTrace();
		} catch (IOException e) {
			Toast toast = Toast.makeText(context,
					"I/O error. Reason: " + e.getMessage(), Toast.LENGTH_SHORT);
			toast.show();
			e.printStackTrace();
		}

		return null;
	}
	
}
